#include <fs/fs.h>
#include <xen/time.h>
#include <xen/init.h>

struct inode *ramfs_get_inode(struct super_block *sb, int mode, unsigned int dev)
{
	struct inode * inode = new_inode(sb);

	if (inode) {
		inode->i_mode = mode;
		//inode->i_uid = current_fsuid();
		//inode->i_gid = current_fsgid();
		//inode->i_mapping->a_ops = &ramfs_aops;
		//inode->i_mapping->backing_dev_info = &ramfs_backing_dev_info;
		//mapping_set_gfp_mask(inode->i_mapping, GFP_HIGHUSER);
		//mapping_set_unevictable(inode->i_mapping);
		//inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
		/*
		switch (mode & S_IFMT) {
		default:
			init_special_inode(inode, mode, dev);
			break;
		case S_IFREG:
			inode->i_op = &ramfs_file_inode_operations;
			inode->i_fop = &ramfs_file_operations;
			break;
		case S_IFDIR:
			inode->i_op = &ramfs_dir_inode_operations;
			inode->i_fop = &simple_dir_operations;

			// directory inodes start off with i_nlink == 2 (for "." entry) 
			inc_nlink(inode);
			break;
		case S_IFLNK:
			inode->i_op = &page_symlink_inode_operations;
			break;
		}
		*/
	}
	return inode;
}

static int ramfs_fill_super(struct super_block * sb, void * data, int silent)
{
	struct inode * inode;
	struct dentry * root;

	//sb->s_maxbytes = MAX_LFS_FILESIZE;
	//sb->s_blocksize = PAGE_CACHE_SIZE;
	//sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
	//sb->s_magic = RAMFS_MAGIC;
	//sb->s_op = &ramfs_ops;
	sb->s_time_gran = 1;
	//inode = ramfs_get_inode(sb, S_IFDIR | 0755, 0);
	if (!inode)
		return -ENOMEM;

	root = d_alloc_root(inode);
	if (!root) {
		//iput(inode);
		return -ENOMEM;
	}
	sb->s_root = root;
	return 0;
}

static int rootfs_get_sb(struct file_system_type *fs_type,
	int flags, const char *dev_name, void *data, struct vfsmount *mnt)
{
	return get_sb_nodev(fs_type, flags|MS_NOUSER, data, ramfs_fill_super,
			    mnt);
}

static struct file_system_type rootfs_fs_type = {
	.name		= "rootfs",
	.get_sb		= rootfs_get_sb,
	//.kill_sb	= kill_litter_super,
};

int __init init_rootfs(void)
{
	int err;

	//err = bdi_init(&ramfs_backing_dev_info);
	//if (err)
	//	return err;

	err = register_filesystem(&rootfs_fs_type);
	//if (err)
	//	bdi_destroy(&ramfs_backing_dev_info);

	return err;
}
